package com.example.demo.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Created with Software Dept.
 * <p>
 * User: tianbaolei
 * Date: 2019-01
 * Time: 09 16:03
 * Description:
 */
public class JSONUtil {
    private static ObjectMapper OBJECT_MAPPER;
    static {
        OBJECT_MAPPER = new ObjectMapper();
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> T parseJson(String jsonStr, Class<T> parametrized) {
        try {
            return OBJECT_MAPPER.readValue(jsonStr, parametrized);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    public static <T> T parseJson(String jsonStr, Class<?> parametrized, Class<?> parametersFor, Class<?>... parameterClasses) {
        JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(parametersFor, parameterClasses);
        try {
            return OBJECT_MAPPER.readValue(jsonStr, javaType);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    public static String toJson(Object object) {
        try {
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    public static String toJsonWithException(Object object) throws JsonProcessingException {
        return OBJECT_MAPPER.writeValueAsString(object);
    }
}
